using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using Common;
using Common.NotifyEvent;

namespace SProject.Rule
{
	public class SimpleRule : NotifyPropertyChanged
	{
		private bool _Use;

		private ObservableCollection<RuleItem> _Items = new ObservableCollection<RuleItem>();

		public bool Use
		{
			get
			{
				return _Use;
			}
			set
			{
				_Use = value;
			}
		}

		public ObservableCollection<RuleItem> Items
		{
			get
			{
				return _Items;
			}
		}

		public SimpleRule Clone()
		{
			SimpleRule simpleRule = new SimpleRule();
			simpleRule.Use = Use;
			foreach (RuleItem item in Items)
			{
				simpleRule.Items.Add(item.Clone());
			}
			return simpleRule;
		}

		public void SaveToStream(StreamEx stream)
		{
			stream.Write(PropertyKey.Key_SimpleRule);
			List<PropertyKey> list = new List<PropertyKey>();
			List<byte[]> list2 = new List<byte[]>();
			list.Add(PropertyKey.Key_UseSimpleRule);
			list2.Add(BytesConverter.GetBytes(Use));
			list.Add(PropertyKey.Key_Items);
			StreamEx streamEx = new StreamEx();
			streamEx.Write(BytesConverter.GetBytes(Items.Count));
			foreach (RuleItem item in Items)
			{
				item.SaveToStream(streamEx);
			}
			list2.Add(streamEx.ToArray());
			streamEx.Close();
			stream.Write(PropertyKey.Key_Index);
			stream.WriteIndex(list, list2);
			stream.Flush();
		}

		public bool ReadFromStream(StreamEx stream)
		{
			PropertyKey propertyKey = stream.ReadKey();
			if (propertyKey == PropertyKey.Key_SimpleRule)
			{
				propertyKey = stream.ReadKey();
				if (propertyKey == PropertyKey.Key_Index)
				{
					List<PropertyKey> keys;
					List<byte[]> dates;
					stream.ReadIndex(out keys, out dates);
					for (int i = 0; i < keys.Count; i++)
					{
						switch (keys[i])
						{
						case PropertyKey.Key_UseSimpleRule:
							Use = BytesConverter.BytesToBool(dates[i]);
							break;
						case PropertyKey.Key_Items:
						{
							StreamEx streamEx = new StreamEx();
							streamEx.Write(dates[i]);
							streamEx.Seek(0L, SeekOrigin.Begin);
							int num = streamEx.ReadInt();
							for (int j = 0; j < num; j++)
							{
								RuleItem ruleItem = new RuleItem();
								ruleItem.ReadFromStream(streamEx);
								Items.Add(ruleItem);
							}
							streamEx.Close();
							break;
						}
						}
					}
					return true;
				}
				stream.Seek(-4L, SeekOrigin.Current);
				while (true)
				{
					switch (stream.ReadKey())
					{
					case PropertyKey.Key_UseSimpleRule:
						Use = stream.ReadBool();
						break;
					case PropertyKey.Key_Item:
					{
						int num2 = stream.ReadInt();
						for (int k = 0; k < num2; k++)
						{
							RuleItem ruleItem2 = new RuleItem();
							ruleItem2.ReadFromStream(stream);
							Items.Add(ruleItem2);
						}
						break;
					}
					default:
						stream.Seek(-4L, SeekOrigin.Current);
						return true;
					}
				}
			}
			stream.Seek(-4L, SeekOrigin.Current);
			return false;
		}
	}
}
